package com.tianji.remark.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tianji.api.client.learning.LearningClient;
import com.tianji.api.dto.LikedTimesDTO;
import com.tianji.api.vo.ReplyVO;
import com.tianji.common.autoconfigure.mq.RabbitMqHelper;
import com.tianji.common.constants.Constant;
import com.tianji.common.constants.MqConstants;
import com.tianji.common.exceptions.ForbiddenException;
import com.tianji.common.utils.UserContext;
import com.tianji.remark.domain.dto.LikeRecordFormDTO;
import com.tianji.remark.domain.po.LikedRecord;
import com.tianji.remark.domain.po.LikedStat;
import com.tianji.remark.mapper.LikedRecordMapper;
import com.tianji.remark.service.ILikedRecordService;
import com.tianji.remark.service.ILikedStatService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 点赞记录表 服务实现类
 * </p>
 *
 * @author whx
 * @since 2025-01-03
 */
//@Service
public class LikedRecordServiceImpl extends ServiceImpl<LikedRecordMapper, LikedRecord> implements ILikedRecordService {

    @Autowired
    private LearningClient learningClient;

    @Autowired
    private ILikedStatService likedStatService;

    @Autowired
    private RabbitMqHelper rabbitMqHelper;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void like(LikeRecordFormDTO dto) {
        Long userId = UserContext.getUser();

        // 判断bizId是否存在
        ReplyVO bean = learningClient.getIRById(dto.getBizId());
        if(ObjectUtil.isNull(bean)){
            throw new ForbiddenException("该数据已被删除");
        }

        // 判断是不是取消点赞
        LikedRecord likedRecord = lambdaQuery()
                .eq(LikedRecord::getBizId, dto.getBizId())
                .eq(LikedRecord::getUserId, userId)
                .one();

        // 点赞true
        if(dto.getLiked()){
            // 是否已点赞
            if(ObjectUtil.isNotNull(likedRecord)){
                throw new ForbiddenException("您已经点赞过了");
            }

            // 点赞
//            redisTemplate.opsForSet().add()
            likedRecord = BeanUtil.toBean(dto, LikedRecord.class);
            likedRecord.setUserId(userId);

            save(likedRecord);
        }else {
            // 取消点赞 false
            if(ObjectUtil.isNull(likedRecord)){
                throw new ForbiddenException("您未点赞过");
            }

            // 取消点赞
            baseMapper.deleteById(likedRecord.getId());
        }

        //likedStatService.updateLikedTimes(dto);

        // 统计该bizId的liked插入统计表
        Integer count = lambdaQuery()
                .eq(LikedRecord::getBizId, dto.getBizId())
                .eq(LikedRecord::getBizType, dto.getBizType())
                .count();

        LikedStat likedStat = BeanUtil.toBean(likedRecord, LikedStat.class);
        likedStat.setLikedTimes(count);

        likedStatService.save(likedStat);

        LikedTimesDTO likedTimesDTO = BeanUtil.toBean(likedStat, LikedTimesDTO.class);

        // 通知mq同步点赞数
        if(dto.getBizType().equals(Constant.QUESTION_ANSWER)){
            rabbitMqHelper.send(MqConstants.Exchange.LIKE_RECORD_EXCHANGE, MqConstants.Key.QA_LIKED_TIMES_KEY, likedTimesDTO);
        }else {
            rabbitMqHelper.send(MqConstants.Exchange.LIKE_RECORD_EXCHANGE, MqConstants.Key.NOTE_LIKED_TIMES_KEY, likedTimesDTO);
        }
    }

    @Override
    public List<Long> likedBizList(List<Long> bizIds) {
        // 查询当前用户的点赞id集合
        Long userId = UserContext.getUser();

        List<LikedRecord> recordList = lambdaQuery()
                .eq(LikedRecord::getUserId, userId)
                .in(LikedRecord::getBizId, bizIds)
                .list();

        return recordList.stream().map(LikedRecord::getBizId).collect(Collectors.toList());
    }

    @Override
    public void readLikedTimesAndSendMessage(String bizType, int maxBizSize) {

    }
}
